/*
 * #%L
 * SwiftUIWeb Maven Webapp
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
/*
 * Copyright 2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.linkwithweb.products.swiftui.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.linkwithweb.products.swiftui.context.EntityContext;
import com.linkwithweb.products.swiftui.context.SystemContext;
import com.linkwithweb.products.swiftui.dataobject.FrameworkReportColumn;
import com.linkwithweb.products.swiftui.dataobject.FrameworkTextReport;
import com.linkwithweb.products.swiftui.spring.jdbc.DatabaseResult;
import com.linkwithweb.products.swiftui.ui.model.RequestCondition;

/**
 * @author ashwin kumar
 * 
 */
@Controller
public class QueryBrowser extends AbstractController {
	private static List<String> valueToIgnore = null;
	static {
		valueToIgnore = new ArrayList<String>();
		valueToIgnore.add("entityName");
		valueToIgnore.add("opts");
		valueToIgnore.add("id");
	}

	/**
	 * Constructor
	 */
	public QueryBrowser() {
	}

	/**
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @return
	 */
	@RequestMapping("/queryBrowser")
	public ModelAndView ricoController(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		String querySQL = getRequestParamter("reportSQL");
		String id = getRequestParamter("reportId");
		String _fmt = httpServletRequest.getParameter("_fmt");
		
		if (StringUtils.isBlank(querySQL) && StringUtils.isBlank(id)) {
			return new ModelAndView("querybrowser/component_querybrowser");
		}

		
		if(StringUtils.isNotBlank(_fmt) && StringUtils.equalsIgnoreCase(_fmt,"xl")){
			try {
				httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL("export/"+"QUERY_" + SystemContext.getInstance().getClientName().get()+"?mediUser=admin&mediPass=252a2df5"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return new ModelAndView("redirect:/");
		}
		
		
		String originalId = getRequestParamter("id");
		String distinct = getRequestParamter("distinct");
		String edit = getRequestParamter("edit");
		String page_size = getRequestParamter("page_size");
		String offset = getRequestParamter("offset");
		String reportName = getRequestParamter("reportName");
		/**
		 * If report SQL is Not Null and if offset and page_size are null then
		 * return definition
		 */

		if (StringUtils.isBlank(page_size) && StringUtils.isBlank(offset)) {
			EntityContext entityContext = new EntityContext();
			entityContext.setEntityName(id);

			/**
			 * Try to load Metadata For Report Object
			 */
			FrameworkTextReport reportObject = getPlatformService().loadReportFromSQL(querySQL);
			if (reportObject.getConditions() != null)
				reportObject.getConditions().clear();

			if (reportObject != null) {

				/**
				 * If Report Columns are not configured load the default
				 * MetaData from SQL RUN
				 */

				Map paramMap = new HashMap();
				paramMap.put("context", reportObject);

				return new ModelAndView("querybrowser/querybrowser_component_def", paramMap);
			}
		} else {
			/**
			 * Return Data
			 */
			/**
			 * Try to load Metadata For Report Object
			 */
			FrameworkTextReport reportObject = getPlatformService().loadReportFromSQL(querySQL);
			if (reportObject.getConditions() != null)
				reportObject.getConditions().clear();

			/**
			 * If we have to return LOV Filters
			 */
			/**
			 * Append any Custom Filters
			 */
			handleCustomFilters(reportObject);

			/**
			 * Append any Rico Filters
			 */
			handleRicoFilters(reportObject);

			DatabaseResult databaseResult = getPlatformService().loadReportDataFromSQL(querySQL,reportObject);

			Map paramMap = new HashMap();
			paramMap.put("context", databaseResult);
			return new ModelAndView("querybrowser/querybrowser_data", paramMap);
		}

		/**
		 * Now lets build query which can handle limits
		 */

		return new ModelAndView("blank", new HashMap());
	}

	/**
	 * @param requestObject
	 * @param request
	 * @param reportComponent
	 * 
	 */
	protected void handleCustomFilters(FrameworkTextReport reportComponent) {
		/**
		 * Custom Filters are of Form FILTER_<COLUMN_NAME>
		 * f[1][op]=LIKE&f[1][len]=1&f[1][0]=*ca*
		 */
		String filterValue = null;
		String filterCondition = null;

		for (FrameworkReportColumn reportColumn : reportComponent.getColumns()) {
			String paramName = "F_DATE_" + reportColumn.getColumnName();

			filterValue = getRequestParamter("FILTER_DATE_" + reportColumn.getColumnName());
			filterCondition = getRequestParamter("CONDITION_FILTER_DATE_" + reportColumn.getColumnName());

			if (StringUtils.isBlank(filterValue)) {
				filterValue = getRequestParamter("FILTER_DATETIME_" + reportColumn.getColumnName());
				filterCondition = getRequestParamter("CONDITION_FILTER_DATETIME_" + reportColumn.getColumnName());
				paramName = "F_DATETIME_" + reportColumn.getColumnName();
			}

			if (StringUtils.isBlank(filterValue)) {
				filterValue = getRequestParamter("FILTER_" + reportColumn.getColumnName());
				filterCondition = getRequestParamter("CONDITION_FILTER_" + reportColumn.getColumnName());
				paramName = reportColumn.getColumnName();
			}

			if (filterValue != null) {
				RequestCondition filter = new RequestCondition();
				filter.setKey(paramName);
				filter.setValue(filterValue);
				filter.setCondition(filterCondition);

				reportComponent.getConditions().add(filter);
			}
		}
	}

	/**
	 * @param requestObject
	 * @param request
	 * @param reportComponent
	 * 
	 */
	protected void handleRicoFilters(FrameworkTextReport reportComponent) {
		/**
		 * Rico Filters are of Form
		 * s0=ASC&f[0][op]=LIKE&f[0][len]=1&f[0][0]=*c*&
		 * f[1][op]=LIKE&f[1][len]=1&f[1][0]=*ca*
		 */
		int index = 0;
		String filterValue = null;
		String sortClause = null;
		for (FrameworkReportColumn reportColumn : reportComponent.getColumns()) {
			filterValue = getRequestParamterWithNoEvaluation("f[" + index + "][0]");
			if (filterValue != null) {
				RequestCondition filter = new RequestCondition();
				filter.setKey(reportColumn.getColumnName());
				filter.setValue(filterValue);
				filter.setCondition(getRequestParamterWithNoEvaluation("f[" + index + "][op]"));
				if (filter.getValue().trim().equalsIgnoreCase("")) {
					continue;
				}
				reportComponent.getConditions().add(filter);
			}

			sortClause = getRequestParamterWithNoEvaluation("s" + index);
			if (StringUtils.isNotBlank(sortClause)) {
				reportComponent.setOrderByCluase("`" + reportColumn.getColumnName() + "` " + sortClause);
			}

			index = index + 1;
		}

	}

}
